//
// Created by xbm on 23-3-10.
//
#include "log.h"
#include <thread>
#include <utility>
#include "eventLoop.h"
#include "dispatcher.h"
#include "handler.h"

using namespace std;
using namespace event;

void EventLoop::addEvent(shared_ptr<Event> e) {
    events_.push(std::move(e));
}

void EventLoop::loop() {
    log("eventLoop start looping!");

    Dispatcher &dispatcher = Dispatcher::getInstance();
    while (!done_) {
        while (auto event = events_.pop())
            dispatcher.dispatch(*event);
        this_thread::yield();
    }


}

EventLoop::EventLoop() {
    log("eventLoop start running!");
}

EventLoop::~EventLoop() {
    log("eventLoop end running!");

}

void EventLoop::loopBackground() {
    log("eventLoop start background running!");

    thread t(&EventLoop::loop, this);
    t.detach();
}

void EventLoop::init() {
    log("eventLoop initiating!");
    registerHandles();
    ResultSupervisorHandler::getInstance().run();
}

void EventLoop::close() {
    log("eventLoop closing!");

    if (!done_)
        done_ = true;
}

